﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PasswordSecurity.cs" company="Mar3ek">
//   This code is licensed under the Mozilla Public License 2.0.
//   You can find the full license text at the following address:
//   https://winkee.codeplex.com/license
// </copyright>
// <summary>
//   Defines the PasswordSecurity type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace WinKee
{
    using System;
    using System.Runtime.InteropServices.WindowsRuntime;
    using System.Text;

    using Windows.Security.Cryptography.Core;

    internal static class PasswordSecurity
    {
        public static string ProtectAppPassword(string password)
        {
            var kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);

            var key = kdf.CreateKey(Encoding.UTF8.GetBytes(password).AsBuffer());

            var hashed =
                Convert.ToBase64String(
                    CryptographicEngine.DeriveKeyMaterial(
                        key,
                        KeyDerivationParameters.BuildForPbkdf2(
                            Encoding.UTF8.GetBytes("WinKee@CodePlex").AsBuffer(),
                            10000),
                        32).ToArray());

            return hashed;
        }

        public static bool VerifyAppPassword(string password, string targetHash)
        {
            var kdf = KeyDerivationAlgorithmProvider.OpenAlgorithm(KeyDerivationAlgorithmNames.Pbkdf2Sha256);

            var key = kdf.CreateKey(Encoding.UTF8.GetBytes(password).AsBuffer());

            var hashed =
                Convert.ToBase64String(
                    CryptographicEngine.DeriveKeyMaterial(
                        key,
                        KeyDerivationParameters.BuildForPbkdf2(
                            Encoding.UTF8.GetBytes("WinKee@CodePlex").AsBuffer(),
                            10000),
                        32).ToArray());

            return hashed == targetHash;
        }
    }
}
